import request from '@/utils/request'
import axios from "axios";
import { getToken } from '@/utils/auth'

const baseURL = process.env.VUE_APP_BASE_API

// 查询文件列表
export function listFile (query) {
  return request({
    url: '/file/list',
    method: 'get',
    params: query
  })
}
/** 获取全部图片 */
export function getAllImages (query) {
  return request({
    url: '/file/getAllImages',
    method: 'get',
    params: query
  })
}
/** 获取全部图片 */
export function getAllImagesCompare (partIds,fieldIds) {
  return request({
    url: '/file/getAllImagesCompare?partIds='+partIds+'&fieldIds='+fieldIds,
    method: 'get'
  })
}
// 查询文件详细
export function getFile (id) {
  return request({
    url: '/file/' + id,
    method: 'get'
  })
}

// 新增文件
export function addFile (data) {
  return request({
    url: '/file',
    method: 'post',
    data: data
  })
}

// 修改文件
export function updateFile (data) {
  return request({
    url: '/file',
    method: 'put',
    data: data
  })
}

// 删除文件
export function delFile (id) {
  return request({
    url: '/file/' + id,
    method: 'delete'
  })
}

// 下载文件
export function downloadFile (id) {

  axios.get(
    baseURL + '/file/fileDownload?fileId=' + id, {
      responseType: "blob",
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((response) => {
    const isBlob = response.data.type !== 'application/json'
    if (isBlob) {
      const blob = new Blob([response.data])

      const elink = document.createElement('a');
      // let fileName = response.headers["content-disposition"].substring(response.headers["content-disposition"].indexOf("="+1));
      let fileName = response.headers["content-disposition"].substring(response.headers["content-disposition"].indexOf("=") + 1);
      elink.download = chineseFromUtf8Url(fileName.split(".")[0]) + "." + fileName.split(".")[1];
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      this.printErrMsg(res.data);
    }
  });

}
// 查看文件--
export function fileView (id,type) {
  // 跟vue.config.js中保持一致
  const port = process.env.VUE_APP_SERVER_PORT// 端口*/
  return request({
    //  url: '/file/fileView?fileId=' + id + `&url=http://localhost:${port}`,
    // url: '/file/fileView?fileId=' + id,
    url: '/file/fileView?fileId=' + id + '&type='+type,
    method: 'get'
  })
}

// 打开文件--
export function openFileView (id) {
  // 跟vue.config.js中保持一致
  // const port = process.env.VUE_APP_SERVER_PORT// 端口*/
  return request({
    // url: '/file/openFileView?fileId=' + id + `&url=http://localhost:${port}`,
    url: '/file/openFileView?fileId=' + id,
    method: 'get'
  })
}

// 如将UTF-8编码字符串“%E6%B1%89%E5%AD%97”的中文为“<汉字>”
//UTF-8编码的汉字转换为字符，特殊字符未处理，
function chineseFromUtf8Url (strUtf8) {
  var bstr = "";
  var nOffset = 0; //   processing   point   on   strUtf8

  if (strUtf8 == "")
    return "";

  strUtf8 = strUtf8.toLowerCase();
  nOffset = strUtf8.indexOf("%e");
  if (nOffset == -1)
    return strUtf8;

  while (nOffset != -1) {
    bstr += strUtf8.substr(0, nOffset);
    strUtf8 = strUtf8.substr(nOffset, strUtf8.length - nOffset);
    if (strUtf8 == "" || strUtf8.length < 9)       //   bad   string
      return bstr;

    bstr += utf8CodeToChineseChar(strUtf8.substr(0, 9));
    strUtf8 = strUtf8.substr(9, strUtf8.length - 9);
    nOffset = strUtf8.indexOf("%e");
  }

  return bstr + strUtf8;
}

function utf8CodeToChineseChar (strUtf8) {
  var iCode, iCode1, iCode2;
  iCode = parseInt("0x" + strUtf8.substr(1, 2));
  iCode1 = parseInt("0x" + strUtf8.substr(4, 2));
  iCode2 = parseInt("0x" + strUtf8.substr(7, 2));

  return String.fromCharCode(((iCode & 0x0F) << 12) |
    ((iCode1 & 0x3F) << 6) |
    (iCode2 & 0x3F));
}
export function downloadResourceFile (path) {
  let url = baseURL + "/file/download/resource?resource=" + encodeURIComponent(path);
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then((res) => {
    const isBlob = res.data.type !== 'application/json'
    if (isBlob) {
      const blob = new Blob([res.data]);
      this.saveAs(blob, decodeURIComponent(res.headers['download-filename']))
    } else {
      this.printErrMsg(res.data);
    }
  })
}



export function materialdownload (id) {

  axios.get(
    baseURL + '/web/app/materialdownload?fileId=' + id, {
      responseType: "blob",
      headers: { 'Authorization': 'Bearer ' + getToken() }
    }).then((response) => {
    const isBlob = response.data.type !== 'application/json'
    if (isBlob) {
      const blob = new Blob([response.data])

      const elink = document.createElement('a');
      // let fileName = response.headers["content-disposition"].substring(response.headers["content-disposition"].indexOf("="+1));
      let fileName = response.headers["content-disposition"].substring(response.headers["content-disposition"].indexOf("=") + 1);
      elink.download = chineseFromUtf8Url(fileName.split(".")[0]) + "." + fileName.split(".")[1];
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else {
      this.printErrMsg(res.data);
    }
  });

}
